package iDirection;

import java.io.*;
import java.util.ArrayList;
import java.util.Scanner;

public final class ConfigMsgID {

	public static ArrayList<String> ResultMsgId = new ArrayList<String>();

	public static String[] getMsgID(String RoomID) {
		
		ConfigMsgID parser = new ConfigMsgID("C:\\Temp\\test.txt");
		
		try {
			parser.processLineByLine(RoomID);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		
		String[] targetList = new String[ResultMsgId.size()];
		
		for (int i = 0; i < ResultMsgId.size(); i++) {
			targetList[i] = ResultMsgId.get(i);
		}

		return targetList;
	}

	/**
	 * @param aFileName
	 *            full name of an existing, readable file.
	 */
	public ConfigMsgID(String aFileName) {
		fFile = new File(aFileName);
	}

	/** Template method that calls {@link #processLine(String)}. */
	public final void processLineByLine(String resultRoom)
			throws FileNotFoundException {
		Scanner scanner = new Scanner(fFile);
		try {
			// first use a Scanner to get each line
			while (scanner.hasNextLine()) {
				processLine(scanner.nextLine(), resultRoom);
			}
		} finally {
			// ensure the underlying stream is always closed
			scanner.close();
		}
	}

	/**
	 * Overridable method for processing lines in different ways.
	 * 
	 * <P>
	 * This simple default implementation expects simple name-value pairs,
	 * separated by an '=' sign. Examples of valid input :
	 * <tt>height = 167cm</tt> <tt>mass =  65kg</tt>
	 * <tt>disposition =  "grumpy"</tt>
	 * <tt>this is the name = this is the value</tt>
	 */
	public void processLine(String aLine, String resultRoom) {
		// use a second Scanner to parse the content of each line
		Scanner scanner = new Scanner(aLine);
		scanner.useDelimiter("=");
		if (scanner.hasNext()) {
			String Room = scanner.next();
			String MsgID = scanner.next();
			if (Room.equals(resultRoom))
				ResultMsgId.add(MsgID.trim());
		} else {
			log("Empty or invalid line. Unable to process.");
		}

		scanner.close();
	}

	// PRIVATE //
	private final File fFile;

	private static void log(Object aObject) {
		System.out.println(String.valueOf(aObject));
	}
}
